<template>
  <div class="mpnewsEditArea">
    
    <!-- 富文本框 -->
    <!-- 文件上传input 将它隐藏-->
    <el-upload accept=".jpg,.png.,.gif"
      :action="serverUrl"
      :data="fileUpload"
      :show-file-list="false"
      :before-upload="(file)=>{return uploadBefore(file,'image')}"
      :on-success="(response,res,fileList,type)=>{return uploadSuccess(response,res,fileList,'image')}"
      :on-error="(err, file, fileList)=>{return uploadError(err, file, fileList,'image')}"
      >
    </el-upload>
    <div class="left_con">
      <div class="title_input">
        <el-input placeholder="在此输入标题" v-model="mpnews[current].title" clearable></el-input>
        <quill-editor ref="myQuillEditor" :options="quillOption"
          v-model="mpnews[current].content"
          @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
          @ready="onEditorReady" @change="onEditorChange"
          class="editor" />
      </div>
      <div class="add_fun dis-flex flex-lc">
        <div class="img-box face">
          <img v-if="mpnews[current].imgUrl" class="img-cover" :src="mpnews[current].imgUrl"/>
        </div>
        <el-upload class="upload-demo" accept=".jpg,.png.,.gif"
          :action="serverUrl"
          :data="fileUpload"
          :show-file-list="false"
          :before-upload="(file)=>{return uploadBefore(file,'image')}"
          :on-success="(response,res,fileList,type)=>{return uploadSuccess(response,res,fileList,'face')}"
          :on-error="(err, file, fileList)=>{return uploadError(err, file, fileList,'image')}"
          ref="cover">
          <template v-if="!mpnews[current].imgUrl">
            <el-button type="text">添加封面图</el-button>
            建议尺寸：1068*455
          </template>
          <template v-else>
            <el-button type="text">更改封面图</el-button>
          </template>
        </el-upload>
      </div>
      <div class="add_fun dis-flex flex-sbc">
        <p class="appLabel">摘要：</p>
        <el-input type="textarea" class="input-textarea" autosize
          placeholder="选填" v-model="mpnews[current].digest" resize="none">
        </el-input>
      </div>
      <div class="add_fun dis-flex flex-sbc">
        <p class="appLabel">作者：</p>
        <el-input type="textarea" class="input-textarea" autosize
          placeholder="选填" v-model="mpnews[current].author" resize="none">
        </el-input>
      </div>
    </div>
    <!--left-->
    <div class="right_con" v-if="mpnews.length > 0">
      <div class="onlyOne" v-if="mpnews.length == 1">
        <div class="item" @click="selectItem(0)">
          <div class="img-box face">
            <img class="img-cover" :src="mpnews[0].imgUrl" :alt="mpnews[0].title">
          </div>
          <div class="title text-overflow">{{ mpnews[0].title }}</div>
          <div class="desc text-overflow">{{ mpnews[0].digest }}</div>
        </div>
      </div>
      <div class="gtOne" v-else>
        <div :class="['item','item_'+ak,(current==ak)?'active':'']"
          v-for="(art,ak) in mpnews" :key="ak"  @click="selectItem(ak)">
          <div class="img-box face">
            <img class="img-cover" :src="art.imgUrl" :alt="art.title">
          </div>
          <div class="title text-overflow">{{ art.title }}</div>
          <div class="delete_mask">
            <i class="el-icon-delete-solid" @click="delMpnewsItem(ak)"></i>
          </div>
        </div>
      </div>
      <div class="add_btn" @click="addMpnewsItem()" v-show="mpnews.length < 7">
        <i class="el-icon-plus"></i>
      </div>
    </div>
    <!--right缩略图-->
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import * as Quill from 'quill';

import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { quillEditor } from 'vue-quill-editor';

import resizeImage from 'quill-image-resize-module';//调整大小组件
import { ImageDrop } from 'quill-image-drop-module';//拖动加载图片组件

Quill.register('modules/resizeImage', resizeImage);
Quill.register('modules/imageDrop', ImageDrop);

let fontSizeStyle = Quill.import('attributors/style/size');
fontSizeStyle.whitelist = ['12px', '14px', false, '18px', '20px', '24px']
Quill.register(fontSizeStyle, true)

import { toolbarOptions } from '../materialLibrary/quill.conf';//目前没用

export default {
  name:"mpnewsEdit",
  components:{
    quillEditor,
  },
  computed:{...mapState(['',]),},
  inheritAttrs:false,
  inject: ['mpnews','serverUrl','qiniuaddr'],
  data() {
    return {
      isDev:process.env.NODE_ENV == 'development',
      draft:[{
        detail_Id:0,//主键Id
        title:"",//标题
        digest:"",//摘要,描述
        author:"",//作者
        content_source_url:"",//点击 阅读原文跳转的页面连接
        content:"",//内容
        imgUrl:null,//缩略图URL
        thumb_media_id:null,//缩略图meidiaId
      }],
      defDraft:[{
        detail_Id:0,//主键Id
        title:"",//标题
        digest:"",//摘要,描述
        author:"",//作者
        content_source_url:"",//点击 阅读原文跳转的页面连接
        content:"",//内容
        imgUrl:null,//缩略图URL
        thumb_media_id:null,//缩略图meidiaId
      }],
      current:0,//基础指向,用来标记编辑到mpnews的索引,默认0
      quillOption: {
        // Some Quill options...
        placeholder: "请输入正文",
        //  富文本编辑器配置
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              'image': function(value) {
                if (value) {
                  document.querySelector('.avatar-uploader input').click()
                } else {
                  this.quill.format('image', false);
                }
              }
            },
          },
          imageDrop: true,
          imageResize: {}
        },
        theme: 'snow'
      },
      fileUpload: { //附件上传
        file: null,
        token:''
      },
    }
  },
  
  methods: {
    selectItem(idx){
      console.log(idx)
      this.current = idx;
      // 防止富文本框进入页面就显示指针
      this.$refs.myQuillEditor.quill.enable(false);
      setTimeout(res=>{
        this.$refs.myQuillEditor.quill.enable(true)
      },1000)
    },
    onEditorBlur(e){},//失焦
    onEditorFocus(e){},//获焦
    onEditorReady(quill){},
    onEditorChange(e){},
    uploadBefore(file,type) {
      let typeObj = (function(){
        return {
          image:{txt:'图片',arr:["image/png","image/jpeg"],sizeMax:1024 * 1024 * 10},
          video:{txt:'视频',arr:["video/mp4"],sizeMax:1024 * 1024 * 10},
          file:{txt:'文件',arr:[],sizeMax:1024 * 1024 * 10},
        }[type]
      })(type)

      if(typeObj.arr.length > 0 && !typeObj.arr.includes(file.type)){
        this.$message({
          message: '文件的格式不正确,请上传正确文件',
          type: 'warning'
        });
        return false;
      }
      if(file.size > typeObj.sizeMax){
        this.$message({
          message: '上传的文件过大',
          type: 'warning'
        });
        return false;
      }
      this.fileUpload.file = file;
      return this.$api.getQiniuToken().then(res=>{
        this.fileUpload.token = res.data.data;
      })
    },
    uploadSuccess(response,res,fileList,type){
      if(!("key" in response)){ return }
      if(type == "image"){
        // 首先获取富文本编辑器的实例
        let quill = this.$refs.myQuillEditor.quill;
        // 获取光标所在位置
        let idx = quill.selection.savedRange.index;
        // 插入图片res为服务器返回的数据https://qiniuoss.chenxi618.com/loading.gif
        quill.insertEmbed(idx, 'image', `${this.qiniuaddr}/${response.key}`)
        // 光标移动至文本末端
        quill.setSelection(idx + 1)
      }
      if(type == "face"){
        this.$set( this.mpnews[this.current],'imgUrl',`${this.qiniuaddr}/${response.key}`);
        this.$set( this.mpnews[this.current],'faceName',res.name);
        this.$set( this.mpnews[this.current],'thumb_media_id',null);
      }
    },
    uploadError() {
      this.$message.error('图片插入失败')
    },
    addMpnewsItem() {
      let addObj = {
        detail_Id:'',
        title: "",
        digest: "",
        author: "",
        content: "",
        imgUrl: "",
        thumb_media_id: null,
        eS_Company_Id: null
      }
      this.mpnews.push(addObj)
      this.current = this.mpnews.length - 1;
    },// 手动增加图文列表
    delMpnewsItem(idx) {
      this.mpnews.splice(idx,1)
      this.selectItem(0);
    },// 手动删除图文列表
  },
  beforeDestroy(){}
}
</script>


<style lang="less" scoped>
.dis-ib{
  display:inline-block;
}
img{
  max-width:100%;
}
.mpnewsEditArea{
  width:100%;
  @rw:unit( (268 + 40),px);
  .left_con{
    min-height:500px;
    margin-right:@rw;
  }
  .right_con{
    position: absolute;
    top:25px;right:0;
    width:@rw;
    padding-left:40px;
  }
}
.left_con{
  .add_fun{
    padding:15px;
    border-bottom: 1px solid #d9d9d9;
    .input-textarea{
      flex:1 1 auto;
      position: relative;
      display: inline-block;
      vertical-align: bottom;
      font-size: 14px;
    }
  }
  .face{
    width:112px;height:48px;
    margin-right:20px;
  }
  .appLabel{
    flex:0 0 3em;
    width:3em;
  }
}
.right_con{
  .onlyOne{
    .face{
      height:114px;
      background-color:#ddd;
    }
    .title{
      text-align: left;
      font-size:16px;
      margin:10px 0;
      padding:0 12px;
      color:#111;
    }
    .desc{
      text-align: left;
      font-size:14px;
      padding:0 12px;
      color:#999;
    }
  }
  .gtOne{
    .item{
      text-align: left;
      font-size:16px;
      line-height:20px;
      height:60px;
      border:1px solid #e4e6e9;
      background-color:#fff;
      &.active{
        border-color:#0c4c7f;
      }
      .face{
        position: absolute;
        top:10px;bottom:10px;right:10px;
        width:40px;height:40px;
      }
      .title{
        text-align: left;
        line-height:40px;
        position: relative;
        padding-left:10px;
        padding-right:60px;
        padding-top:10px;
        padding-bottom:10px;

      }
      .delete_mask{
        display:none;
      }
      &:hover .delete_mask{
        display:block;
        position: absolute;
        bottom:0;left:0;right:0;
        text-align:right;
        padding:2px 10px 0;
        background-color:rgba(0,0,0,0.5);
        color:#999;
      }
    }
    .item_0{
      height:144px;
      .face{
        position: relative;
        top:0px;bottom:0px;left:0;right:0px;
        width:100%;height:144px;
      }
      .title{
        position: absolute;
        left:0;right:0;bottom:0;
        text-align: left;
        padding:20px 10px 10px;
        background-image: linear-gradient(-180deg,transparent,rgba(0,0,0,0.35));
        color:#fff;
      }
    }
  }
  .add_btn{
    text-align: center;
    font-size:16px;
    line-height:60px;
    height:60px;
    border:1px solid #e4e6e9;
    background-color:#fff;
  }
}

</style>
